package com.ljf.admin.controller;


import com.ljf.admin.POJO.SysMenu;
import com.ljf.admin.POJO.SysRole;
import com.ljf.admin.service.SysRoleService;
import com.ljf.framework.util.tree.TreeObject;
import com.ljf.framework.util.tree.TreeUtil;
import com.ljf.framework.result.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Auther: lijinfeng
 * @Date: 2022/4/26
 * @Description 描述:
 */
@RestController
@RequestMapping("/system/role")
public class RoleController {

    @Autowired
    private SysRoleService sysRoleService;

    @GetMapping("/{userId}")
    public JsonResult getRolesByUserId(@PathVariable Long userId) {
        List<SysRole> roleList = sysRoleService.getRolesByUserId(userId);
        return JsonResult.success(roleList);
    }

    @GetMapping("/list")
    public JsonResult list() {
        List<SysRole> roleList = sysRoleService.getList();
        return JsonResult.success(roleList);
    }

    @PutMapping("/{userId}/setRoleId")
    public JsonResult setRoleId(@PathVariable Long userId, @RequestBody Long roleId) {
        if (1L == userId)
            return JsonResult.error("admin用户不可以修改角色");
        sysRoleService.setRoleId(userId, roleId);
        return JsonResult.success();
    }


    /**
     * 删除roleId的菜单权限列表
     *
     * @param roleId
     * @param menus
     * @return
     */
    @DeleteMapping("/{roleId}/menu/{menus}")
    public JsonResult deleteRoleMenu(@PathVariable(value = "roleId") Long roleId, @PathVariable Long... menus) {
        List<SysMenu> thisRoleMenuList = sysRoleService.deleteRoleMenu(roleId, menus);
        List<TreeObject> tree = TreeUtil.getTree(thisRoleMenuList);
        return JsonResult.success(tree);
    }

    @PostMapping
    public JsonResult addRole(@RequestBody SysRole sysRole) {
        sysRoleService.addRole(sysRole);
        return JsonResult.success("角色添加成功");
    }

    @PutMapping
    public JsonResult editRole(@RequestBody SysRole sysRole) {
        sysRoleService.editRole(sysRole);
        return JsonResult.success("角色修改成功");
    }


    @DeleteMapping
    public JsonResult deleteRole(Long roleId) {
        sysRoleService.deleteRole(roleId);
        return JsonResult.success("角色删除成功");
    }
}
